package com.example.orderdemo.controller;

import com.example.orderdemo.beans.Result;
import com.example.orderdemo.beans.User;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {

    // 声明了RestTemplate
    private final RestTemplate restTemplate;

    // 当bean 没有无参构造函数的时候，spring将自动拿到有参的构造函数，参数进行自动注入
    public OrderController(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }


    /**
     * 访问远程服务-查询
     * @return
     */
    @RequestMapping("/order")
    public String order(){
        Result forObject = restTemplate.getForObject("http://localhost:8080/userController/{id}", Result.class, 1);
        return forObject.toString();
    }

    /**
     * 访问远程服务-添加用户
     * @return
     */
    @RequestMapping("/addOrder")
    public String addOrder(){

        //服务提供者和服务消费者两者的User构造函数都要有一个无参构造函数
        User user = new User("test","HongKong");
        ResponseEntity<Result> resultResponseEntity = restTemplate.postForEntity("http://localhost:8080/userController/add",
                user, Result.class);
        System.out.println(resultResponseEntity.toString());
        System.out.println(resultResponseEntity.getBody().toString());
        return resultResponseEntity.getBody().toString();
    }

    /**
     * 访问远程服务-修改用户
     * @return
     */
    @RequestMapping("/editOrder")
    public String editOrder(){

        //服务提供者和服务消费者两者的User构造函数都要有一个无参构造函数
        User user = new User(1,"test","editOrder");
        //修改方法
//        restTemplate.put("http://localhost:8080/userController/editUser", user, Result.class);
        //使用execute方法实现增删改查需求
        HttpEntity<User> httpEntity = new HttpEntity<>(user);
        ResponseEntity<Result> exchange = restTemplate.exchange("http://localhost:8080/userController/editUser",
                HttpMethod.PUT, httpEntity, Result.class);
        return exchange.getBody().toString();
    }

    /**
     * 访问远程服务-删除用户
     * @return
     */
    @RequestMapping("/deleteOrder")
    public String deleteOrder(){
        //删除方法
//        restTemplate.delete("http://localhost:8080/userController/{id}",1);
        //使用execute方法实现增删改查需求
        ResponseEntity<Result> exchange = restTemplate.exchange("http://localhost:8080/userController/{id}",
                HttpMethod.DELETE, null, Result.class,1);
        return exchange.getBody().toString();
    }


}
